#-- coding:UTF-8 --
from flask import Flask,request,render_template,flash,redirect,url_for,send_from_directory,jsonify,json,session
from flask_sqlalchemy import SQLAlchemy
from wtforms import TextField
import config
from forms import userNameForm
from flask_login import LoginManager,login_required,current_user,login_user,logout_user
from flask_login import UserMixin
import os,time
from werkzeug import secure_filename
import random
#import pymysql
#pymysql.install_as_MySQLdb()    # mysql+mysqldb
import sys
reload(sys)
sys.setdefaultencoding('utf-8')


app = Flask(__name__,static_folder='./static', static_url_path='')
app.config['JSON_AS_ASCII'] = False
app.config.from_object(config)
db = SQLAlchemy(app)
lm = LoginManager(app)
# 设置上传文件存放的目录

class Users(db.Model):
    """用户表"""
    __tablename__="users"
    id=db.Column(db.Integer,primary_key=True,autoincrement=True)
    name=db.Column(db.String(100),nullable=False)
    password=db.Column(db.String(100),nullable=False)
    email=db.Column(db.String(100),nullable=False)
    description=db.Column(db.String(100),nullable=True)
    portrait=db.Column(db.String(100),nullable=True)
    department=db.Column(db.String(100),nullable=True)

class Tweets(db.Model):
    """用户上传的图片博文表"""
    __tablename__="tweets"
    id=db.Column(db.Integer,primary_key=True,autoincrement=True)
    image=db.Column(db.String(100),nullable=False)
    user_id=db.Column(db.Integer,db.ForeignKey('users.id'))
    time=db.Column(db.Integer,nullable=False)
    description=db.Column(db.String(100),nullable=True)
    favor = db.Column(db.Integer,nullable=False)
    user = db.relationship('Users',backref=db.backref('tweets'))


class Likes(db.Model):
    """图片博文点赞表"""
    __tablename__="likes"
    id=db.Column(db.Integer,primary_key=True,autoincrement=True)
    time=db.Column(db.Integer,nullable=False)
    user_id=db.Column(db.Integer,db.ForeignKey('users.id'))
    tweet_id=db.Column(db.Integer,db.ForeignKey('tweets.id'))

    user = db.relationship('Users',backref=db.backref('liked'))
    tweet = db.relationship('Tweets',backref=db.backref('likes'))

class Comments(db.Model):
    """图片博文点赞表"""
    __tablename__="comments"
    id=db.Column(db.Integer,primary_key=True,autoincrement=True)
    user_id=db.Column(db.Integer,db.ForeignKey('users.id'))
    tweet_id=db.Column(db.Integer,db.ForeignKey('tweets.id'))
    comment=db.Column(db.String(100),nullable=False)
    time=db.Column(db.Integer,nullable=False)


    user = db.relationship('Users',backref=db.backref('commented'))
    tweet = db.relationship('Tweets',backref=db.backref('comments'))

class Following(db.Model):
    """用户关注表"""
    __tablename__="following"
    id=db.Column(db.Integer,primary_key=True,autoincrement=True)
    time=db.Column(db.Integer,nullable=False)
    following_id=db.Column(db.Integer,nullable=False)

    user_id=db.Column(db.Integer,db.ForeignKey('users.id'))

    user = db.relationship('Users',backref=db.backref('following'))


class Followers(db.Model):
    """用户粉丝表"""
    __tablename__ = "followers"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    time = db.Column(db.Integer, nullable=False)
    follower_id = db.Column(db.Integer, nullable=False)

    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))

    user = db.relationship('Users', backref=db.backref('followers'))

class webUser(UserMixin):
    pass

db.create_all()
def queryUser(id):
    return Users.query.filter(Users.id==id).first()
@lm.user_loader
def load_user(id):
    if queryUser(id) is not None:
        curr_user = webUser()
        curr_user.id = id
        return curr_user

@lm.request_loader
def load_user_from_request(request):
    id = request.args.get('token')
    if queryUser(id) is not None:
        curr_user = User()
        curr_user.id = id
        return curr_user

@app.route('/')
def hello_world():
    return render_template('index.html')

@app.route('/api/registe' , methods=["POST","GET"] )
def userRegiste():#用户注册
    userForm = userNameForm()
    if request.method =='GET':#GET方式返回注册界面
        return render_template('registe.html',form=userForm)
    elif request.method =='POST':#POST访问进行注册
        name = userForm.name.data#用户名
        email = userForm.email.data#用户电子邮件
        passwordOne = userForm.passwordOne.data#用户密码
        passwordTwo = userForm.passwordTwo.data#确认密码
        if name and passwordOne and passwordTwo:
            if passwordOne == passwordTwo:
                user = Users.query.filter(Users.email==email).first()
                if user == None:
                    user1 = Users(name=name,email=email,password=passwordOne)
                    db.session.add(user1)
                    db.session.commit()
                    return render_template('success.html')
                else:
                    return render_template('registe.html',form=userForm,msg='email has been registe')
            else:
                return render_template('registe.html',form=userForm,msg='password not same , input again')
        else:
            return render_template('registe.html',form=userForm)

@app.route('/api/login' , methods=['POST','GET'] )
def userlogin():
    next = request.args.get('next')
    uform = userNameForm()
    if request.method =='GET':
        return render_template('login.html',form = uform)
    else:
        useremail = request.form.get('email')
        userpassword = request.form.get('passwordOne')
        user = Users.query.filter(Users.email==useremail).first()
        if user.password == userpassword:
            curr_user = webUser()
            curr_user.id = user.id
            login_user(curr_user)
            portrait =  '/image/default.jpg' if user.portrait is None else user.portrait
            results = {}
            results['status'] = 0
            results['portrait'] = portrait
            results['name'] = user.name
            return results
        else:
            results={}
            results['status'] = 1
            results['msg'] = 'wrong username or password'
            return results

@app.route('/api/index')
def index():
    return render_template('index.html')

@app.route('/addUser')
@login_required
def addUser_func(): #增加一个名为 "张三" 的用户
    user1 = Users(name="张三",email="zhangsan@cqu.edu.cn",password=123)
    db.session.add(user1)
    db.session.commit()
    return 'add user success'

@app.route('/api/logout')
@login_required
def logout():
    logout_user()
    return 'Logged out successfully!'

@app.route('/editUserInfo')
def editUserInfo_func(): # 张三在个人中心修改自己的个人信息  增加个人简介和所在地
    user = Users.query.filter(Users.name=="张三" and Users.email=="zhangsan@cqu.edu.cn").first()

    description=db.Column(db.String(100),nullable=True)
    portrait=db.Column(db.String(100),nullable=True)
    department=db.Column(db.String(100),nullable=True)

    user.description = '我是一名程序员'
    user.portrait = '/var/mobile/portrait/zhangsan.png'
    user.department = 'xxx 公司'
    db.session.commit()
    return ' id is %d , editUserInfo success' %user.id



@app.route('/sendTweet')
def sendTweet_func(): # 发送图片
    id = 1 # 获取当前用户id
    image = '/var/mobile/picture/niceday.png'
    time = 1911012344 #获取当前时间戳
    description = 'What a nice day!'

    tweet = Tweets(image=image,user_id=id,time=time,description=description)

    db.session.add(tweet)
    db.session.commit()
    return ' send tweet success'

# 设置请求内容的大小限制，即限制了上传文件的大小
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024
UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['png','PNG','jpg','JPG','gif','GIF'])
# 检查文件类型是否合法
def allowed_file(filename):# 判断文件的扩展名是否在配置项ALLOWED_EXTENSIONS中
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/api/up_pic',methods=['GET','POST'])
def up_pic():
    if request.method == 'POST':
        # 获取上传过来的文件对象
        file = request.files['file']
        # 检查文件对象是否存在，且文件名合法
        if file and allowed_file(file.filename):
            # 去除文件名中不合法的内容
            filename = secure_filename(file.filename)
            # 将文件保存在本地UPLOAD_FOLDER目录下
            file.save(os.path.join(UPLOAD_FOLDER, filename))
            ######对数据库进行操作
            return 'Upload Successfully'
        else:    # 文件不合法
            return 'Upload Failed'
    else:    # GET方法
        return render_template('upload.html')
#下载图片
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(UPLOAD_FOLDER, filename)

@app.route('/up/<filename>')
def up(filename):
    return os.path.join(UPLOAD_FOLDER, filename)

@app.route('/getTweetform/<int:order>')
def getRecentTweet_func(order): # 获取最新发布的图片   
    tweets = Tweets.query.order_by(Tweets.time.desc())[order:order+20]
    # time = 1911012343 #当前时间
    # tweets = Tweets.query.filter(Tweets.time > time - 100).all() #获取最近一小时发布的 图片
    for tweet in tweets:
        print('tweet id is %d , img path is : %s'%(tweet.id,tweet.image))
    return ' success'


lm.login_message = 'Unauthorized User'
lm.login_message_category = "info"
lm.login_view = 'userlogin'

@app.route('/initHeaderPic',methods=["POST","GET"])
def initHeaderPic():
    result = {
        "picpathes":[
            "/uploads/1.jpg",
            "/uploads/2.jpg",
            "/uploads/2.jpg",
            "/uploads/4.jpg"
        ]
    }
    return jsonify(result)

#获取首页
@app.route('/index',methods=["POST","GET"])
def getHeaderPage():
    return render_template('index.html')
 
#获取最热图片网页
@app.route('/trend',methods=["POST","GET"])
def getTrendPage():
    return render_template('trend.html')
    
#获取上传网页
@app.route('/upload',methods=["POST","GET"])
def getUploadPage():
    return render_template('upload.html')

#获取最新图片网页
@app.route('/latest',methods=["POST","GET"])
def getLatestPage():
    return render_template('latest.html')

#跳转到个人信息界面
@app.route('/profile',methods=["POST","GET"])
def getProfilePage():
    return render_template('profile.html')

#跳转到点赞信息界面
@app.route('/like',methods=["POST","GET"])
def getLikePage():
    return render_template('like.html')

#跳转到关注信息界面
@app.route('/follow',methods=["POST","GET"])
def getFollowPage():
    return render_template('follow.html')

#跳转到个人相册界面
@app.route('/gallery',methods=["POST","GET"])
def getGalleryPage():
    return render_template('gallery.html')

#跳转到查看图片界面
@app.route('/seepicinfo/<int:tweet_id>',methods=["POST","GET"])
def seePicInfo(tweet_id):
    return render_template('picture.html',img_id=tweet_id)

#跳转到查看作者界面
@app.route('/seeauthorinfo/<int:author_id>',methods=["POST","GET"])
def seeAuthorInfo(author_id):
    return render_template('authorinfo.html',user_id=author_id)

#处理用户上传过来的图片
@app.route('/uploadpicture',methods=["POST"])
def getUploadPicture():
    result = {}
    if 'user_id' in session:
        user_id = session.get('user_id')
        user = Users.query.filter(Users.id==user_id).first()
        if user is None:
            result['status'] = '1'
            result['info']='用户不存在'
            return result
    else:
        result['status'] = '1'
        result['info']='用户未登陆，请先登陆'
        return result
    #imglist = request.files('imgs');
    #print(imglist)
    user_id = session.get('user_id')
    picnames = request.form.get('picnames')
    tags = request.form.get('tags')
    description = request.form.get('description')
    #print(picnames)
    namelist = picnames.split(',')
    taglist = tags.split(',')
    #print(namelist)
    for picname in namelist:
        #print(picname)
        file =  request.files.get(picname)
        #print(file)
        # 检查文件对象是否存在，且文件名合法
        if file:#if allowed_file(file.filename):
            # 去除文件名中不合法的内容
            #filename = secure_filename(file.filename)
            # 将文件保存在本地UPLOAD_FOLDER目录下
            fname =  str(user_id)+picname
            file.save(os.path.join(UPLOAD_FOLDER,fname))
            ######对数据库进行操作
            ts = time.time()
            tweet = Tweets(image = fname,user_id = user_id,time = int(ts),description =description,favor=0)
            db.session.add(tweet)
            db.session.commit()
        else:    # 文件不合法
            return 'Upload Failed'
    return 'Upload Succeed'
 
@app.route('/register' , methods=["POST"] )
def register():#用户注册
    print(request.form)
    data = json.loads(request.form.get('data'))
    print(data)
    name = data['user_name']
    email = data['email']
    passwordOne = data['input_password']
    passwordTwo = data['comfirm_password']
    result = {'result':None,'info':None}
  
    if name and passwordOne and passwordTwo:
        if passwordOne == passwordTwo:
            user = Users.query.filter(Users.email==email).first()
            if user == None:
                user1 = Users(name=name,email=email,password=passwordOne,portrait='default.jpg')
                db.session.add(user1)
                db.session.commit()
                user = Users.query.filter(Users.email==email).first()
                session['user_id'] = user.id
                print(user.id)
                result['result'] = '0'
                result['info'] = '注册成功'
                result['user_id'] = user.id
                return jsonify(result);
            else:
                result['result'] = '1'
                result['info'] = '邮箱已被注册'
                return jsonify(result);
        else:
            result['result'] = '2'
            result['info'] = '两次密码不一致'
            return jsonify(result);
    else:
        result['result'] = '2'
        result['info'] = '用户名或密码为空'
        return jsonify(result);

@app.route('/login' , methods=["POST"] )
def login():#用户登录
    #print(request.form)
    data = json.loads(request.form.get('data'))
    print(data)
    result = {'status':None,'info':None}
    name = data['user_name']
    pwd = data['password']
    user = Users.query.filter(Users.name==name,Users.password==pwd).first()
    if user == None:
        result['status'] = '1'
        result['info']='用户不存在或密码错误'
        return jsonify(result);
    else:
        session['user_id'] = user.id
        result['status'] = '0'
        result['info']='登录成功'
        result['user_id']=user.id
        result['user_img']=UPLOAD_FOLDER + '/' + user.portrait
        return jsonify(result);

@app.route('/islogin' , methods=["GET","POST"] )
def islogin():#跳转页面时判断用户是否已登录
    user_id = session.get("user_id");
    result = {'status':None,'info':None}
    if user_id == None:
        result['status'] = '1'
        result['info']='用户未登录'
        return jsonify(result);
    else:
        user = Users.query.filter(Users.id == user_id).first()
        if user == None:
            result['status'] = '2'
            result['info']='用户不存在'
            return jsonify(result);
        else:
            session['user_id'] = user.id
            result['status'] = '0'
            result['info']='用户已登录'
            result['user_id']=user.id
            result['user_name']=user.name
            result['user_img']=UPLOAD_FOLDER + '/' + user.portrait
            return jsonify(result);

@app.route('/logout', methods=["GET","POST"])
def userLogout():#用户登出
    result = {'status': None, 'info': None}
    session['user_id'] = None
    result['status'] = '0'
    result['info'] = '用户已登出'
    return jsonify(result)
###根据id获取用户头像地址
def getUserImgFromId(id):
    user = Users.query.filter(Users.id == id).first()
    if user.portrait==None or user.portrait =='':
        return './uploads/user_img/default.png'
    return user.portrait

###根据id获取用户名称
def getUserNameFromId(id):
    user = Users.query.filter(Users.id == id).first()
    if user == None or user.name == None:
        return 'default'
    return user.name
def getUserEmailFromId(id):
    user = Users.query.filter(Users.id == id).first()
    if user.email == None or user == None:
        return 'example@cqu.com'
    return user.email
###根据图片id获取图片点赞数
def getFavorFromTweetId(id):
    tweet = Tweets.query.filter(Tweets.id ==id).first()
    return tweet.favor
def getUserIdFromTweetId(id):
    tweet = Tweets.query.filter(Tweets.id ==id).first()
    return tweet.user_id
    
#获取主页的四张推荐图
@app.route('/api/recommendIndex')
def recommendIndex():
    tweets = Tweets.query.all()
    lenth = len(tweets)
    random.shuffle(tweets)
    img = []
    for i in range(4):
        tweet = tweets[i]
        temp = {}
        temp['tweet_id'] = tweet.id
        temp['user_id'] = getUserIdFromTweetId(tweet.id)
        temp['imgaddr'] = UPLOAD_FOLDER+'/'+tweet.image
        temp['userimg'] = UPLOAD_FOLDER+'/'+getUserImgFromId(tweet.user_id)
        temp['username'] = getUserNameFromId(tweet.user_id)
        temp['favor'] = getFavorFromTweetId(tweet.id)
        temp['time'] = tweet.time
        img.append(temp)
    return jsonify(img)

@app.route('/api/RecentTweetIndex')#在主页获得4张最新图片
def RecentTweetIndex():
    tweets = Tweets.query.order_by(Tweets.time.desc())[0:4]
    img = []
    for tweet in tweets:
        temp = {}
        temp['tweet_id'] = tweet.id
        temp['user_id'] = getUserIdFromTweetId(tweet.id)
        temp['imgaddr'] = UPLOAD_FOLDER+'/'+tweet.image
        temp['userimg'] = UPLOAD_FOLDER+'/'+getUserImgFromId(tweet.user_id)
        temp['username'] = getUserNameFromId(tweet.user_id)
        temp['favor'] = getFavorFromTweetId(tweet.id)
        temp['time'] = tweet.time
        img.append(temp)
    return jsonify(img)

@app.route('/api/HotTweetIndex')#在主页获得4张最热图片
def HotTweetIndex():
    tweets = Tweets.query.order_by(Tweets.favor.desc())[0:4]####如何查询！
    img = []
    for tweet in tweets:
        temp = {}
        temp['tweet_id'] = tweet.id
        temp['user_id'] = getUserIdFromTweetId(tweet.id)
        temp['imgaddr'] = UPLOAD_FOLDER+'/'+tweet.image
        temp['userimg'] = UPLOAD_FOLDER+'/'+getUserImgFromId(tweet.user_id)
        temp['username'] = getUserNameFromId(tweet.user_id)
        temp['favor'] = getFavorFromTweetId(tweet.id)
        temp['time'] = tweet.time
        img.append(temp)
    return jsonify(img)

#获取最新的图片信息
@app.route('/latestpic/<int:id>',methods=["POST","GET"])
def getLatestPicture(id):
    result = {}
    if id == 0:
        tweets = Tweets.query.order_by(Tweets.id.desc())[0:20]
    else:
        tweets = Tweets.query.filter(Tweets.id < id).order_by(Tweets.time.desc())[0:20]
    img = []
    if tweets == None:
        result['status'] = '1'
        result['info'] = '已无图片'
    for tweet in tweets:
        result['status'] = '0'
        temp = {}
        temp['tweet_id'] = tweet.id
        temp['user_id'] = getUserIdFromTweetId(tweet.id)
        temp['imgaddr'] = UPLOAD_FOLDER+'/'+tweet.image
        temp['userimg'] = UPLOAD_FOLDER+'/'+getUserImgFromId(tweet.user_id)
        temp['username'] = getUserNameFromId(tweet.user_id)
        temp['favor'] = getFavorFromTweetId(tweet.id)
        temp['time'] = tweet.time
        img.append(temp)
    result['imgs']=img
    return jsonify(result)

#获取最热的图片信息
@app.route('/hotpic/<int:order>',methods=["POST","GET"])
def getHotPicture(order):
    result = {}
    tweets = Tweets.query.order_by(Tweets.favor.desc()).all()
    if len(tweets)-1<order:
        result['status'] = '2'
        result['info'] = '没有那么多张图片'
        return jsonify(result)
    elif len(tweets)<order+20:
        tweets = tweets[order:]
    else:
        tweets = tweets[order:order+20]
    img = []
    if tweets == None:
        result['status'] = '1'
        result['info'] = '已无图片'
    for tweet in tweets:
        result['status'] = '0'
        temp = {}
        temp['tweet_id'] = tweet.id
        temp['user_id'] = getUserIdFromTweetId(tweet.id)
        temp['imgaddr'] = UPLOAD_FOLDER+'/'+tweet.image
        temp['userimg'] = UPLOAD_FOLDER+'/'+getUserImgFromId(tweet.user_id)
        temp['username'] = getUserNameFromId(tweet.user_id)
        temp['favor'] = getFavorFromTweetId(tweet.id)
        temp['time'] = tweet.time
        img.append(temp)
    result['imgs']=img
    return jsonify(result)

#点赞:需不需要取消赞
@app.route('/api/favor')
def favor():
    user_id = session.get("user_id");
    tweet_id = request.args.get('tweet_id')
    if user_id == None:
        result={}
        result['status']= 1
        result['info'] = '用户未登录'
        return jsonify(result)
    tweet = Tweets.query.filter(Tweets.id == tweet_id).first()
    print(tweet)
    if tweet == None :
        result={}
        result['status']= 2
        result['info'] = '没有这张图片'
        return jsonify(result)
    like1 = Likes.query.filter(Likes.tweet_id==tweet_id,Likes.user_id==user_id).first()
    #print(like1)
    if like1 == None :
        like2 = Likes(time=int(time.time()),user_id = user_id,tweet_id = tweet_id)
        db.session.add(like2)
        tweet.favor = tweet.favor+1
        db.session.commit()
        result = {}
        result['status'] = 0
        result['info'] = '点赞成功'
    else:
        db.session.delete(like1)
        tweet.favor = tweet.favor - 1
        db.session.commit()
        result = {}
        result['status'] = 3
        result['info'] = '取消点赞成功'
    return jsonify(result)
#当前登陆用户关注对应图片用户
@app.route('/api/follow')
def follow():
    follower_id = session.get("user_id")
    user_id = request.args.get('user_id')
    if follower_id == None:
        result={}
        result['status']=1
        result['info'] = '用户未登录'
        return jsonify(result)
    user = Users.query.filter(Users.id == user_id).first()
    if user == None :
        result={}
        result['status']=2
        result['info'] = '没有该用户'
        return jsonify(result)
    follow = Followers.query.filter(Followers.user_id == user_id,Followers.follower_id==follower_id).first()
    if follow == None :
        follow1 = Followers(time = int(time.time()),user_id = user_id,follower_id = follower_id)
        db.session.add(follow1)
        db.session.commit()
        result = {}
        result['status'] = 0
        result['info'] = '关注成功'
        return jsonify(result)
    else:
        db.session.delete(follow)
        db.session.commit()
        result = {}
        result['status'] = 3
        result['info'] = '取消关注成功'
        return result
#查看单张图片
@app.route('/api/seepicinfo/<int:tweet_id>')
def seepicinfo(tweet_id):
    result={}
    tweet = Tweets.query.filter(Tweets.id == tweet_id).first()
    if tweet == None :
        result['status']=2
        result['info'] = '没有这张图片'
        return jsonify(result)
    user_id = tweet.user_id
    result['status'] = '0';
    result['username'] = getUserNameFromId(user_id)
    result['userimg'] = UPLOAD_FOLDER+'/'+getUserImgFromId(tweet.user_id)
    result['author_id'] = user_id
    #result['useremail'] = getUserEmailFromId(user_id)
    result['imgaddr'] = UPLOAD_FOLDER+'/'+tweet.image
    result['description'] = tweet.description
    cur_user_id = session.get("user_id")
    if cur_user_id == None:
        result['follow'] = 0
        result['like'] = 0
    else:
        follow = Followers.query.filter(Followers.follower_id == cur_user_id,Followers.user_id == user_id).first()
        like1 = Likes.query.filter(Likes.user_id==cur_user_id,Likes.tweet_id==tweet_id).first()
        if follow == None :
            result['follow'] = 0
        else:
            result['follow'] = 1
        if like1 == None :
            result['like'] = 0
        else:
            result['like'] = 1
    return jsonify(result)

#用户主页
@app.route('/api/userindex/<int:user_id>')
def userIndex(user_id):
    result = {};
    user = Users.query.filter(Users.id == user_id).first()
    if user == None:
        result['status'] = '1'
        result['info'] = '无该用户'
        return jsonify(result)
    else:
        userinfo={}
        userinfo['name'] = user.name
        userinfo['email'] = user.email
        userinfo['description'] = user.description
        userinfo['user_img'] = UPLOAD_FOLDER+'/'+user.portrait
        userinfo['department'] = user.department
        result['user'] = userinfo
        tweets = Tweets.query.filter(Tweets.user_id == user_id)[0:20]
        img = []
        for tweet in tweets:
            temp = {}
            temp['tweet_id'] = tweet.id
            temp['imgaddr'] = UPLOAD_FOLDER+'/'+tweet.image
            temp['favor'] = getFavorFromTweetId(tweet.id)
            img.append(temp)
        result['status'] = '0'
        result['imgs']=img
        if 'user_id' in session:
            cur_user_id = session.get('user_id')
            follow1 = Followers.query.filter(Followers.user_id == user_id,Followers.follower_id == cur_user_id).first()
            if follow1 == None:
                result['follow'] = 0
            else:
                result['follow'] = 1
        else:
            result['follow'] = 0
        return jsonify(result)      

#下载图片
@app.route('/download/<int:img_id>',methods=["POST","GET"])
def downloadImg(img_id):
    tweet = Tweets.query.filter(Tweets.id == img_id).first()
    if tweet == None :
        result['status']=1
        result['info'] = '没有这张图片'
        return jsonify(result)
    else:
        return send_from_directory(UPLOAD_FOLDER, tweet.image, as_attachment=True)

@app.route('/edit', methods=["POST"])
def edit():#用户信息修改
    print(request.form)
    data = json.loads(request.form.get('data'))
    print(data)
    name = data['edit_name']
    email = data['edit_email']
    pw = data['edit_password']
    des = data['edit_description']
    dep = data['edit_department']
    result = {'result': None, 'info': None}
    uid = session.get("user_id")
    em = Users.query.filter(Users.email == email).first()
    if em == None or em.id == uid:
        user = Users.query.filter(Users.id == uid).first()
        user.name = name
        user.email = email
        user.password = pw
        user.description = des
        user.department = dep
        db.session.commit()
        result['status'] = '0'
        result['info'] = '修改成功'
        result['user_id'] = user.id
        return jsonify(result)
    else:
        result['status'] = '0'
        result['info'] = '邮箱名已被使用，请重新输入'
        return jsonify(result)

@app.route('/edit_p', methods=["POST"])
def edit_p():#用户头像修改
    print(request.form)
    print(request.files)
    result = {'result': None, 'info': None}
    user_id = session.get('user_id')
    user = Users.query.filter(Users.id == user_id).first()
    if user == None:
        result['status'] = '1'
        result['info'] = '用户不存在'
        return jsonify(result)
    else:
        file = request.files.get('file')
        if file == None:
            result['status'] = '2'
            result['info'] = '未发现头像文件'
            return jsonify(result)
        else:
            filename = file.filename
            suffix = filename.split('.')
            #print(suffix[-1])
            fname =  str(user_id)+ '_portrait.'
            file.save(os.path.join(UPLOAD_FOLDER,fname + suffix[-1]))
            user.portrait = fname + suffix[-1]
            db.session.commit()
            result['status'] = '0'
            result['info'] = '修改成功'
            result['user_id'] = user.id
            return jsonify(result)

#根据tweet_id获得用户的图片
@app.route('/api/getUserTweet')
def getUserTweet():
    user_id = request.args.get("user_id");
    tweet_id = request.args.get('tweet_id')
    user = Users.query.filter(Users.id == user_id).first()
    result = {}
    if user == None:
        result['status'] = '1'
        result['info'] = '无该用户'
        return jsonify(result)
    if tweet_id == '-1':
        tweets = Tweets.query.filter(Tweets.user_id == user_id).order_by(Tweets.id.desc()).limit(10).all()
    else:
        tweets = Tweets.query.filter(Tweets.user_id == user_id,Tweets.id<tweet_id).order_by(Tweets.id.desc()).limit(10).all()
    img = []
    for tweet in tweets:
        temp = {}
        temp['tweet_id'] = tweet.id
        temp['imgaddr'] = UPLOAD_FOLDER+'/'+tweet.image
        temp['favor'] = tweet.favor
        img.append(temp)
    result['status'] = '0'
    result['img'] = img
    return jsonify(result)

@app.route('/getInfo', methods=["GET","POST"])
def getInfo():#返回用户信息
    user_id = session.get("user_id");
    result = {'status': None, 'info': None}
    user = Users.query.filter(Users.id == user_id).first()
    session['user_id'] = user.id
    result['status'] = '0'
    result['user_id'] = user.id
    result['user_name'] = user.name
    result['user_img'] = UPLOAD_FOLDER+'/'+user.portrait
    result['user_email'] = user.email
    result['user_des'] = user.description
    result['user_dep'] = user.department
    return jsonify(result);

def getTweetFromId(id):
    return Tweets.query.filter(Tweets.id==id).first()
    
@app.route('/api/getUserFavor')
def getUserFavor():
    result = {}
    user_id = request.args.get('user_id')
    order = (int)(request.args.get('order'))#order为0表示开始
    likes = Likes.query.filter(Likes.user_id ==user_id).order_by(Likes.time.desc()).all()
    if len(likes)==0 :
        result['status'] = 1
        result['info'] = '点赞记录为空'
    elif len(likes)-1<order:
        result['status'] = 2
        result['info'] = '没有更多点赞记录了'
    elif len(likes)<order+20:
        likes = likes[order:]
    else:
        likes = likes[order:order+20]
    like = []
    for lk in likes:
        result['status'] = 0
        result['info'] = '已获取喜欢的图片'
        tweet = getTweetFromId(lk.tweet_id)
        temp = {}
        temp['tweet_id'] = lk.tweet_id
        temp['imgaddr'] = UPLOAD_FOLDER+'/'+ tweet.image
        like.append(temp)
    result['like'] = like
    return jsonify(result)

#获取用户的关注用户
@app.route('/api/getUserFollow')
def getUserFollow():
    result = {}
    user_id = session.get('user_id')
    followList = Followers.query.filter(Followers.follower_id == user_id)[0:10]
    if followList == None or len(followList) == 0:
        result['status'] = 1
        result['info'] = '无关注的用户'
    else:
        follows = []
        result['status'] = 0
        result['info'] = '已获取关注的用户'
        for follow in followList:
            temp = {}
            user = Users.query.filter(Users.id == follow.user_id).first()
            temp['follow_name'] = user.name
            temp['follow_id'] = user.id
            temp['follow_img'] = UPLOAD_FOLDER + '/' + user.portrait
            follows.append(temp)
        result['follows'] = follows
    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True)
